Exceptions and Exception Handling

Sources

Weiss, Section 2.5

Summary

Exceptions are a formal method used to respond to situations in Java where something unexpected happens (usually, but not always an error). The basic vocabulary reflects the unusual situation:

One segment of code will try to execute;
if an unusual situation occurs, the code will throw an object called an exception.
The calling method can either catch the exception and handle it,
or propagate the exception using the keyword throws in the method header.
Finally, some code executes regardless of whether or not the exception was thrown.

This entire block of code is called a try-catch block.

There are many types of Exceptions (a whole hierarchy):

Hints:

If you want to throw an exception, you need to create one: throw new Exception("Help!!!");

Example: